package com.party.course.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hutool.core.date.DateUtil;
import com.party.common.core.domain.entity.SysUser;
import com.party.common.exception.ServiceException;
import com.party.common.utils.StringUtils;
import com.party.course.domain.ApprovalInfo;
import com.party.course.domain.PlanClass;
import com.party.course.domain.StudentInfo;
import com.party.course.mapper.PlanClassMapper;
import com.party.course.service.IApprovalInfoService;
import com.party.course.service.IStudentInfoService;
import com.party.system.mapper.SysUserMapper;
import com.party.system.service.ISysUserService;
import com.party.system.service.impl.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.party.course.mapper.AmountInfoMapper;
import com.party.course.domain.AmountInfo;
import com.party.course.service.IAmountInfoService;

import cn.hutool.core.util.IdUtil;
import com.party.common.utils.SecurityUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 金额明细Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-29
 */
@Service
public class AmountInfoServiceImpl extends ServiceImpl<AmountInfoMapper, AmountInfo> implements IAmountInfoService {
    @Resource
    private AmountInfoMapper amountInfoMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private PlanClassMapper planClassMapper;
    @Autowired
    private IApprovalInfoService approvalInfoService;

    @Autowired
    private IStudentInfoService studentInfoService;

    @Resource
    private ISysUserService sysUserService;


    /**
     * 查询金额明细
     *
     * @param id 金额明细主键
     * @return 金额明细
     */
    @Override
    public AmountInfo view(String id) {
        return amountInfoMapper.selectAmountInfoById(id);
    }

    @Override
    public List<AmountInfo> findList(AmountInfo amountInfo) {
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            amountInfo.setUserId(SecurityUtils.getUserIdStr());
        }
        List<AmountInfo> amountInfos = amountInfoMapper.selectAmountInfoList(amountInfo);
        for (AmountInfo info : amountInfos) {
            //根据金额明细中的计划课程id查询计划课程信息
            String planClassId = info.getPlanClassId();
            if(StringUtils.isNotEmpty(planClassId)    && StringUtils.isEmpty(info.getPlanClassName())){
                PlanClass planClass = planClassMapper.selectplanClassById(planClassId);
                info.setPlanClassName(planClass==null?"":planClass.getClassName());
                String stuId = planClass.getStuId();
                StudentInfo view = studentInfoService.view(stuId);
                info.setStudentInfo(view);
            }
            String id = info.getId();
            ApprovalInfo  approvalInfo =new  ApprovalInfo();
            approvalInfo.setBusinessId(id);
            List<ApprovalInfo> list = approvalInfoService.findList(approvalInfo);
            info.setApprovalInfo(CollectionUtil.isEmpty(list)?null:list.get(0));
        }
        return amountInfos;
    }

    /**
     * 查询金额明细列表
     *
     * @param amountInfo 金额明细
     * @return 金额明细
     */
    @Override
    public HashMap<String, Object> findListOther(AmountInfo amountInfo) {
        HashMap<String, Object> map = new HashMap<>();
        List<AmountInfo> amountInfos=new ArrayList<>();
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            amountInfo.setUserId(SecurityUtils.getUserIdStr());
            SysUser user = sysUserMapper.selectUserById(SecurityUtils.getUserId());
            //我的余额
            map.put("amount", user.getAmount());
             amountInfos = amountInfoMapper.selectAmountInfoList(amountInfo);
        }else{
            if(StringUtils.isNotEmpty(amountInfo.getPhonenumber())){
                SysUser byPhone = sysUserService.findByPhone(amountInfo.getPhonenumber());
                //我的余额
                map.put("amount", byPhone.getAmount());
                amountInfos = amountInfoMapper.selectAmountInfoList(amountInfo);
            }
        }

        //总收益
        BigDecimal amountAllAdd = BigDecimal.ZERO;
        if (!amountInfos.isEmpty()) {
            for (AmountInfo info : amountInfos) {
                //计算总收益
                if ("0".equals(info.getCountType())) {
                    amountAllAdd = amountAllAdd.add(info.getChangeAmount());
                }


            }
        }
        map.put("amountAllAdd", amountAllAdd);
        //可提现金额
        BigDecimal cash = findCashAmount(SecurityUtils.getUserIdStr());
        map.put("cash", cash);
        return map;
    }

    /**
     * 查询当前用户可提现金额
     *
     * @param userId
     * @return
     */
    @Override
    public BigDecimal findCashAmount(String userId) {
        List<AmountInfo> infos = amountInfoMapper.findByValidTime(userId);
        BigDecimal cash = BigDecimal.ZERO;
        if (!infos.isEmpty()) {
            for (AmountInfo info : infos) {
                String cashStatus = info.getCashStatus();
                if(!"2".equals(cashStatus)){
                    if ("0".equals(info.getCountType())) {
                        cash = cash.add(info.getChangeAmount());
                    }
                    if ("1".equals(info.getCountType())) {
                        cash = cash.subtract(info.getChangeAmount());
                    }
                }

            }
        }
        return cash;
    }


    /**
     * 查询金额明细列表
     *
     * @param validTime 金额明细
     * @param validTime 到账时间
     * @param wageType  0:已到账  1：未到账
     * @return 金额明细
     * @return
     */
    @Override
    public HashMap<String, Object> findListApp(String validTime, String wageType) {
        //根据用户id和有效时间查询金额明细列表
        List<AmountInfo> amountInfos = amountInfoMapper.findListApp(SecurityUtils.getUserIdStr(), validTime);
        if (StrUtil.isNotEmpty(wageType)) {
            if ("0".equals(wageType)) {
                amountInfos = amountInfoMapper.findListApp1(SecurityUtils.getUserIdStr(), validTime);
            } else {
                amountInfos = amountInfoMapper.findListApp2(SecurityUtils.getUserIdStr(), validTime);
            }
        }
        //根据用户id查询用户信息
        SysUser user = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        HashMap<String, Object> map = new HashMap<>();
        //我的余额
        map.put("amount", user.getAmount());
        //总收益
        BigDecimal amountAllAdd = BigDecimal.ZERO;
        //todo 提现功能未做-累计提现
        BigDecimal allCash = BigDecimal.ZERO;
        //如果金额明细列表不为空
        if (!amountInfos.isEmpty()) {
            //遍历金额明细列表
            for (AmountInfo info : amountInfos) {
                //计算总收益
                if ("0".equals(info.getWageType())) {
                    amountAllAdd = amountAllAdd.add(info.getChangeAmount());
                }
                String amountType = "";

                //根据金额明细中的工资类型设置金额类型
                if ("0".equals(info.getWageType())) {
                    amountType = "佣金";
                } else  if("5".equals(info.getWageType())){
                    amountType = "提现";
                } else {
                    amountType = "绩效";
                }
                if("5".equals(info.getWageType())){
                    // 提现
                    QueryWrapper<ApprovalInfo>   approvalInfoQueryWrapper = new QueryWrapper<>();
                    approvalInfoQueryWrapper.eq("business_id",info.getId());
                    List<ApprovalInfo> list = approvalInfoService.list(approvalInfoQueryWrapper);
                    if(CollectionUtil.isNotEmpty( list)){
                        ApprovalInfo approvalInfo = list.get(0);
                        //     * "状态0：待审批；1：通过；2：驳回"
                        String status = approvalInfo.getStatus();
                        if("0".equals(status)){
                            info.setArrivedStatus("待审批");
                        }else if("1".equals(status)){
                            info.setArrivedStatus("通过");
                            allCash=allCash.add(info.getChangeAmount());
                        }else if("2".equals( status)){
                            info.setArrivedStatus("驳回");
                        }
                    }
                }else{
                    //根据金额明细中的计划课程id查询计划课程信息
                    PlanClass planClass = planClassMapper.selectplanClassById(info.getPlanClassId());
                    if (ObjectUtil.isEmpty(planClass)) {
                        continue;
                    }
                    String classType = "";
                    //根据计划课程类型设置课程类型
                    if ("0".equals(planClass.getOrderType())) {
                        classType = "试课";
                    } else {
                        classType = "正式课";
                    }
                    //设置金额明细的名称
                    info.setName(planClass.getStuName() + classType + amountType);

                    String upclassTime = planClass.getClassTime() + "  " + planClass.getStarTime() + "~" + planClass.getEndTime();
                    //设置金额明细的上课时间
                    info.setUpClassTime(upclassTime);
                    String arrivedStatus = "";
                    //比较当前时间与金额明细中的有效时间
                    int comparisonResult = DateUtil.compare(DateUtil.date(), DateUtil.parse(info.getValidTime()));
                    String validStatus = info.getValidStatus();
                    if ("1".equals(validStatus)) {
                        //如果当前时间大于有效时间，则已到账
                        arrivedStatus = "已到账";
                        info.setArrivedTime(info.getValidTime());
                    } else {
                        //否则未到账
                        arrivedStatus = "未到账";
                        info.setArrivedTime("————");
                    }
                    //设置金额明细的到账状态
                    info.setArrivedStatus(arrivedStatus);

                }
;
            }
        }
        //总收益
        map.put("amountAllAdd", amountAllAdd);
        //累计提现
        map.put("allCash", allCash);
        //账单流水列表
        map.put("infos", amountInfos);
        return map;
    }

    /**
     * 新增金额明细
     *
     * @param amountInfo 金额明细
     * @return 结果
     */
    @Override
    @Transactional
    public int add(AmountInfo amountInfo) {
        amountInfo.setId(IdUtil.simpleUUID());
        amountInfo.setDelFlag("0");
        if (StrUtil.isNotEmpty(amountInfo.getWageType()) && "5".equals(amountInfo.getWageType())) {
            if (ObjectUtil.isEmpty(amountInfo.getChangeAmount())) {
                throw new ServiceException("请输入提现金额");
            }
            BigDecimal cashAmount = findCashAmount(SecurityUtils.getUserIdStr());
            if (cashAmount.compareTo(amountInfo.getChangeAmount()) < 0) {
                throw new ServiceException("提现金额不能大于余额");
            }
            //提现
            amountInfo.setUserId(SecurityUtils.getUserIdStr());
            amountInfo.setCountType("1");
            amountInfo.setCashStatus("0");
            amountInfo.setValidStatus("1");
            amountInfo.setValidTime(DateUtil.now());
            // 修改用户余额的逻辑
            SysUser user = sysUserMapper.selectUserById(Long.valueOf(amountInfo.getUserId()));
            System.out.println("=======user.getAmount()user.getAmount()user.getAmount()======"+user.getAmount());
            System.out.println("=======user.getChangeAmount()user.getChangeAmount()user.getChangeAmount()======"+amountInfo.getChangeAmount());
            if (user != null) {
                user.setAmount(user.getAmount().subtract(amountInfo.getChangeAmount()));
                sysUserMapper.updateUser(user);
            }
        }
        int insert = amountInfoMapper.insert(amountInfo);
        if (StrUtil.isNotEmpty(amountInfo.getWageType()) && "5".equals(amountInfo.getWageType())) {
            //提交提现申请
            approvalInfoService.add(ApprovalInfo.builder()
                    .businessType("1")
                    .businessId(amountInfo.getId())
                    .build());

        }

        return insert;
    }

    /**
     * 修改金额明细
     *
     * @param amountInfo 金额明细
     * @return 结果
     */
    @Override
    public int updateEntity(AmountInfo amountInfo) {
        amountInfo.setUpdateTime(DateUtil.date());
        return amountInfoMapper.updateById(amountInfo);
    }

    /**
     * 批量删除金额明细
     *
     * @param ids 需要删除的金额明细主键
     * @return 结果
     */
    @Override
    public int deleteIds(List<String> ids) {
        return amountInfoMapper.deleteAmountInfoByIds(ids);
    }

    /**
     * 删除金额明细信息
     *
     * @param id 金额明细主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return amountInfoMapper.deleteAmountInfoById(id);
    }
}
